package com.imooc.user.stream;

import com.imooc.auth.service.AuthService;
import com.imooc.auth.service.pojo.Account;
import com.imooc.auth.service.pojo.AuthCode;
import com.imooc.auth.service.pojo.AuthResponse;
import lombok.AccessLevel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.Message;

/**
 * @describte:TODO
 * @program:foodie-cloud
 * @author:zhengdp
 * @create:2021-10-10 17:49:39
 **/
@Slf4j
@EnableBinding(
        value = {
                ForceLogoutTopic.class
        }
)
public class UserMessageConsumer {

    @Autowired
    private AuthService authService;

    @StreamListener(ForceLogoutTopic.INPUT)
    public void consumerLogoutMessage(String payload){
        log.info("Force logout user, uid = {}",payload);
        Account account = Account.builder()
                .userId(payload)
                .skipVerification(true)
                .build();
        AuthResponse resp = authService.delete(account);
        if(!AuthCode.SUCCESS.getCode().equals(resp.getCode())){
            log.error("Error occurred when deleting user session,uid={}",account.getUserId());
            throw new RuntimeException("Cannot delete user session");
        }
    }

    /*
    * 1） 重试（配置文件中配置） 单机重试 / re-queue
    * 2) 死信队列 & 服务降级 （抢救）
    * */
    // 降级Fallback
    @ServiceActivator(inputChannel = "force-logout-topic.force-logout-group.errors")
    public void fallback(Message<?> message){
        log.error("Force logout failed");
        // TODO
        // 强制登录 -> inactive user
        // user表 -> flag(active/inactive) -> 不让你下次登录
    }

}
